package com.example.scaletest;

import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.mylibrary.scaleweihgt.LogUtil;
import com.herohan.uvcapp.CameraHelper;
import com.herohan.uvcapp.ICameraHelper;
import com.herohan.uvcapp.ImageCapture;
import com.serenegiant.usb.Size;
import com.serenegiant.utils.FileUtils;
import com.serenegiant.utils.UriHelper;
import com.serenegiant.widget.AspectRatioSurfaceView;

import java.io.File;

public class CameraAct extends Activity {

    private Context context;
    private AspectRatioSurfaceView surface_view;
    private TextView tv_camera;
    private ICameraHelper mCameraHelper;
//    private AspectRatioSurfaceView mCameraViewMain;
    private ICameraHelper.StateCallback mStateListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_act);
        context = this;
        initView();

        setCamera();

    }

    private void setCamera() {
        //UVC摄像头状态回调
        mStateListener = new ICameraHelper.StateCallback() {
            //插入UVC设备
            @Override
            public void onAttach(UsbDevice device) {
                //设置为当前设备（如果没有权限，会显示授权对话框）
                mCameraHelper.selectDevice(device);
            }

            //打开UVC设备成功（也就是已经获取到UVC设备的权限）
            @Override
            public void onDeviceOpen(UsbDevice device, boolean isFirstOpen) {
                //打开UVC摄像头
                mCameraHelper.openCamera();
            }

            //打开摄像头成功
            @Override
            public void onCameraOpen(UsbDevice device) {
                //开始预览
                mCameraHelper.startPreview();

                //获取预览使用的Size（包括帧格式、宽度、高度、FPS）
                Size size = mCameraHelper.getPreviewSize();
                if (size != null) {
                    int width = size.width;
                    int height = size.height;
                    //需要自适应摄像头分辨率的话，设置新的宽高比
                    surface_view.setAspectRatio(width, height);
                }

                //添加预览Surface
                mCameraHelper.addSurface(surface_view.getHolder().getSurface(), false);
            }

            //关闭摄像头成功
            @Override
            public void onCameraClose(UsbDevice device) {
                if (mCameraHelper != null) {
                    //移除预览Surface
                    mCameraHelper.removeSurface(surface_view.getHolder().getSurface());
                }
            }

            //关闭UVC设备成功
            @Override
            public void onDeviceClose(UsbDevice device) {
            }

            //断开UVC设备
            @Override
            public void onDetach(UsbDevice device) {
            }

            //用户没有授予访问UVC设备的权限
            @Override
            public void onCancel(UsbDevice device) {
            }

        };

        //设置SurfaceView的Surface监听回调
        surface_view.getHolder().addCallback(new SurfaceHolder.Callback() {

            //创建了新的Surface
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if (mCameraHelper != null) {
                    //添加预览Surface
                    mCameraHelper.addSurface(holder.getSurface(), false);
                }
            }

            //Surface发生了改变
            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            }

            //销毁了原来的Surface
            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if (mCameraHelper != null) {
                    //移除预览Surface
                    mCameraHelper.removeSurface(holder.getSurface());
                }
            }
        });

        mCameraHelper = new CameraHelper();
        //设置UVC摄像头状态回调
        mCameraHelper.setStateCallback(mStateListener);
    }

    private void initView() {
        surface_view = findViewById(R.id.surface_view);
        tv_camera = findViewById(R.id.tv_camera);


        tv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                File file = new File(Environment.DIRECTORY_DCIM);
                File file = FileUtils.getCaptureFile(context, Environment.DIRECTORY_DCIM, ".jpg");
                LogUtil.e("file=="+file.getAbsolutePath());
                ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(file).build();


                //进行图片抓拍
                mCameraHelper.takePicture(options, new ImageCapture.OnImageCaptureCallback() {
                    //图片抓拍成功
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        Toast.makeText(context,
                                "save \"" + UriHelper.getPath(context, outputFileResults.getSavedUri()) + "\"",
                                Toast.LENGTH_SHORT).show();
                    }

                    //图片抓拍出现错误
                    @Override
                    public void onError(int imageCaptureError, @NonNull String message, @Nullable Throwable cause) {
                        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                    }
                });


            }
        });



    }

    @Override
    protected void onDestroy() {
        mCameraHelper.release();
        super.onDestroy();
    }
}
